package com.jy.modules.cims.costmanage.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleBeanUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.balance.CalculateExpenseHolderI;
import com.jy.modules.cims.component.balance.dto.FeeParamDto;
import com.jy.modules.cims.component.common.service.TCMmCooperorgCostService;
import com.jy.modules.cims.component.common.service.TCMmCostParamService;
import com.jy.modules.cims.component.common.service.TCMmLoanDetailService;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgCostDTO;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCostParamDTO;
import com.jy.modules.cims.data.common.dto.TCMmLoanDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmRaisePlanDTO;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.LoanDetailDto;
import com.jy.modules.cims.data.dto.RaisePlanDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.modules.cims.deal.service.LoanDealService;
import com.jy.modules.cims.loan.service.RaisePlanService;
import com.jy.modules.cims.settle.service.SettleBalanceService;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;

/**
 * @classname: TCMmCostParamController
 * @description: 定义  费用参数 控制层
 * @author:  zhoupeng
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmCostParam")
public class TCMmCostParamController extends BaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmCostParamController.class);

    @Autowired
    @Qualifier("com.jy.modules.platform.tcmmcostparam.service.TCMmCostParamService")
    private TCMmCostParamService service;
    
    @Autowired
	@Qualifier("com.jy.modules.cims.deal.service.DealService")
	public DealService dealService;
    

    @Autowired
	@Qualifier("com.jy.modules.cims.deal.service.LoanDealService")
	public LoanDealService loanDealService;
    
    @Autowired
  	@Qualifier("com.jy.modules.cims.settle.service.SettleBalanceService")
  	public SettleBalanceService settleBalanceService;
    
    
    @Autowired
    @Qualifier("com.jy.modules.platform.tcmmcooperorgcost.service.TCMmCooperorgCostService")
    private TCMmCooperorgCostService cooperOrgCostservice;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.balance.CalculateExpenseHolder")
    private CalculateExpenseHolderI calculateExpenseHolder;
    
	@Autowired
	private RaisePlanService raisePlanService;
	
	@Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmLoanDetailService")
    private TCMmLoanDetailService tCMmLoanDetailService;
	
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/costManage/queryTCMmCostParam");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	model.setViewName("cims/costManage/addTCMmCostParam");
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/costManage/updateTCMmCostParam");
        }else if("toCopy".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/costManage/copyTCMmCostParam");
        }else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/costManage/viewTCMmCostParam");
        }
        
        return model;
    }
    
    /**
     * @author zhoupeng
     * @description:查询分页列表
     * @date 2016-04-05 14:42:15
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmCostParam")
    @ResponseBody
    public DataMsg queryListTCMmCostParam(HttpServletRequest request, TCMmCostParamDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmCostParamDTO> list = service.searchTCMmCostParamByPaging(params.getSearchParams());
        dataMsg.setStatus("ok");
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    

    /**
     * @author zhoupeng
     * @description:新增
     * @date 2016-04-05 14:42:15
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmCostParam")
    @ResponseBody
    public DataMsg insertTCMmCostParam(HttpServletRequest request, TCMmCostParamDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	TCMmCostParamDTO searchCode=new TCMmCostParamDTO();
        	Map<String, Object> searchParams = new HashMap<String, Object>();
        	searchCode.setCostCode(dto.getCostCode());
        	searchParams.put("dto", searchCode);
            QueryReqBean params = new QueryReqBean();
            params.setSearchParams(searchParams);
        	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
    		params.setPageParameter(pageInfo);
            List<TCMmCostParamDTO> list = service.searchTCMmCostParamByPaging(params.getSearchParams());
            //查询费用编号是否重复
            if(list.size()>0){
            	dataMsg.setStatus("erro");
            	dataMsg.setMsg("费用编号重复请重新输入！");
            	
            }else{
            	dto = (TCMmCostParamDTO)super.initDto(dto);
                service.insertTCMmCostParam(dto);
                dataMsg = super.initDataMsg(dataMsg);
                dataMsg.setMsg("新增成功");
                dataMsg.setStatus("ok");
                dataMsg.setData(this.makeJSONData(dto.getId()));
            }

        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	dataMsg.setMsg("新增失败！");
        	logger.error("执行方法insertSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhoupeng
     * @description:编辑
     * @date 2016-04-05 14:42:15
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmCostParam")
    @ResponseBody
    public DataMsg updateTCMmCostParam(HttpServletRequest request, TCMmCostParamDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmCostParamDTO)super.initDto(dto);
           
            service.updateTCMmCostParam(dto);
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setStatus("ok");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	dataMsg.setMsg("修改失败,请查看录入的数据！");
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhoupeng
     * @description:删除
     * @date 2016-04-05 14:42:15
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteTCMmCostParam")
    @ResponseBody
    public DataMsg deleteTCMmCostParam(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			 service.deleteTCMmCostParamByPrimaryKey(dto,ids);
			 dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			dataMsg.setMsg("删除失败！");
			logger.error("执行方法deleteSysResource异常：", e);

		}
        
        return dataMsg;
    }
    /**
     * @author zhoupeng
     * @description:通过主键查询 其明细信息
     * @date 2016-04-05 14:42:15
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmCostParamDTO dto = service.queryTCMmCostParamByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    /**
     * 
     * @param request
     * @param dataMsg
     * @return
     */
    @RequestMapping(value = "/costSumByParam")
    @ResponseBody
    public DataMsg CostSumByParam(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
   	 	String cooperorgCode = (String) this.getParameter("cooperorgCode");
   	 	String dealCode = (String) this.getParameter("dealCode");
   	 	String costCode = (String) this.getParameter("costCode");
   	 	String contractCode = (String) this.getParameter("contractCode");
   	 	String creditPackageName = (String) this.getParameter("creditPackageName");
   	 	Map<String, Object>  param = new HashMap<String, Object>();
   	 	param.put("dealCode", dealCode);//交易流水号
   	 	param.put("creditorStatus", "02");//债权状态
   	 	
		try {
			List<CreditDetailDto> list = dealService.getDealDetailListReturn(param);
			if(list!=null &&list.size()>0){
		   	 	FeeParamDto feeParamDto = new FeeParamDto();
		   	 	feeParamDto.setCreditList(list);
		   	 	feeParamDto.setCooperorgCode(cooperorgCode);
		   	 	feeParamDto.setCostCode(costCode);
		   	 	list = calculateExpenseHolder.holder(feeParamDto);
		   	 	if(list!=null &&list.size()>0){
		   	 		dealService.updateCreditDealDetailToCostFee(list,dealCode);
		   	 		cooperOrgCostMaintain(cooperorgCode,dealCode,costCode,contractCode,creditPackageName);
		   	 		dataMsg.setMsg("已计算，请查看费用！");
		   	 		dataMsg.setStatus("ok");
		   	 	}else{
		   	 		dataMsg.setMsg("费用计算失败！");
		   	 		dataMsg.setStatus("error");
		   	 	}
			}else{
				dataMsg.setMsg("当前流水号下没有可计算的费用！");
	   	 		dataMsg.setStatus("error");
			}
	   	 	
		} catch (Exception e) {
			dataMsg.setMsg("调用费用计算方法失败！");
			dataMsg.setStatus("error");
			dataMsg.failed(e.getMessage());
			logger.error("", e);

		}
        
        return dataMsg;
    }
    
    
    /**
     * 贷款费用计算
     * @author zhangmi
     * @date  2016年8月24日
     * @param request
     * @param dataMsg
     * @return
     */
    @RequestMapping(value = "/calcFeeLoanSum")
    @ResponseBody
    public DataMsg calcFeeLoanSum(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	String dealCode = (String) this.getParameter("dealCode");
    	
    	DealDto searchDto = new DealDto();
    	searchDto.setDealCode(dealCode);
    	try {
			List<TCMmCooperorgDealDTO> list  = dealService.searchDeal(searchDto);
			if(CollectionsUtils.isNotEmpty(list)){
				TCMmCooperorgDealDTO cooperorgDealDto = list.get(0);
				String cooperorgCode = cooperorgDealDto.getCooperorgCode();
				//判断铜板街机构--目前只支持铜板街
				if(CimsConstant.TBJ_COOPERORG_CODE.equals(cooperorgCode)){
					
					String planId = cooperorgDealDto.getPlanId();
					
					TCMmRaisePlanDTO searchRaiseDto = new TCMmRaisePlanDTO();
					searchRaiseDto.setPlanId(planId);
					List<RaisePlanDto> listRaises = raisePlanService.getRaisePlanList(SearchParamUtil.getSearchParam(searchRaiseDto));
					if(CollectionsUtils.isNotEmpty(listRaises)){

						String costCode = listRaises.get(0).getCostCode();
						if(SimpleStringUtils.hasText(costCode)){
							FeeParamDto feeParamDto = new FeeParamDto();
					   	 	feeParamDto.setDealType(CimsConstant.DEAL_TYPE_LOAN_OUT);
					   	 	feeParamDto.setCooperorgCode(cooperorgCode);
					   	 	feeParamDto.setCostCode(costCode);
					   	 	feeParamDto.setPlanId(planId);
					   	    List<LoanDetailDto> listLoanDetails = loanDealService.getLoanDetailByDealCode(dealCode);
					   	    feeParamDto.setLoanList(listLoanDetails);
							List<LoanDetailDto> listLoans = calculateExpenseHolder.loanHolder(feeParamDto);
							loanDealService.updateLoanDetailFeesByList(listLoans);
							loanDealService.updateLoanFeesTotal(dealCode);
							dataMsg.setData(listLoans);
							dataMsg.setStatus("yes");
							dataMsg.setMsg("费用计算完成！");
						}else{
							dataMsg.setStatus("no");
							dataMsg.setMsg("募集计划编号："+planId+"，未配置费用参数编码！");
						}
						
					}else{
						dataMsg.setStatus("no");
						dataMsg.setMsg("募集编号："+planId+"的募集计划获取失败！");
					}
				} else {
					String costCode = (String) this.getParameter("costCode");
					if (SimpleStringUtils.hasText(costCode)) {
						if("-1".equalsIgnoreCase(costCode)){
							dataMsg.setStatus("no");
							dataMsg.setMsg("请选择费用参数！");
							return dataMsg;
						}
						
						TCMmLoanDetailDTO searchLoanDetailDTO = new TCMmLoanDetailDTO();
						searchLoanDetailDTO.setDealCode(dealCode);
						searchLoanDetailDTO.setLoanStatus(CimsConstant.LOAN_FUNDOUT_WIN);
						Map<String, Object> searchParams = new HashMap<String, Object>();
				    	searchParams.put("dto", searchLoanDetailDTO);
						List<TCMmLoanDetailDTO> dataList = tCMmLoanDetailService.searchTCMmLoanDetail(searchParams);
				    	
				    	List<LoanDetailDto> loanList = new ArrayList<LoanDetailDto>();
						LoanDetailDto loanDetailDto = null;
						if (CollectionsUtils.isNotEmpty(dataList)) {
							for (TCMmLoanDetailDTO data : dataList) {
								if (CimsConstant.COST_STATUS_DJ.equals(data.getCostState())
										|| CimsConstant.COST_STATUS_WJ.equals(data.getCostState())
										|| CimsConstant.COST_STATUS_BH.equals(data.getCostState())) {
									loanDetailDto = new LoanDetailDto();
									SimpleBeanUtils.copyBean2Bean(loanDetailDto, data);
									loanList.add(loanDetailDto);
								}
							}
						}
						
						if (CollectionsUtils.isNotEmpty(loanList)) {
							FeeParamDto feeParamDto = new FeeParamDto();
							feeParamDto.setDealType(CimsConstant.DEAL_TYPE_LOAN_OUT);
							feeParamDto.setLoanList(loanList);
							feeParamDto.setCooperorgCode(cooperorgCode);
							feeParamDto.setCostCode(costCode);
							loanList = calculateExpenseHolder.loanHolder(feeParamDto);
							if (CollectionsUtils.isNotEmpty(loanList)) {
								loanDealService.updateLoanDetailFeesByList(loanList);
								loanDealService.updateLoanFeesTotal(dealCode);
								dataMsg.setStatus("yes");
								dataMsg.setMsg("费用计算完成！");
							} else {
								dataMsg.setMsg("费用计算失败！");
								dataMsg.setStatus("error");
							}
						} else {
							dataMsg.setMsg("当前流水号下没有可计算的费用！");
							dataMsg.setStatus("error");
						}
					} else {
						dataMsg.setStatus("no");
						dataMsg.setMsg("交易流水号：" + dealCode + "，未配置费用参数！");
					}
					// dataMsg.setStatus("no");
					// dataMsg.setMsg("目前只支持铜板街费用计算！");
				}
			}
		} catch (Exception e) {
			dataMsg.setStatus("no");
			dataMsg.setMsg("费用计算异常："+e.getMessage());
			dataMsg.setData(ExceptionUtils.getStackTraceAsString(e));
			logger.error("贷款费用计算异常："+ExceptionUtils.getStackTraceAsString(e));
		}
    	return dataMsg;
    }
    /**
     * @author zhoupeng
     * @description: 费用关系维护
     * @date 2016-04-14 14:42:15
     * @param id
     * @return
     */
    private void cooperOrgCostMaintain(String cooperorgCode,String dealCode,String costCode,String contractCode,String creditPackageName) throws AbaboonException {
        //ModelAndView model = new ModelAndView();
        try{
   	 		
   	 	Map<String, Object> searchParams = new HashMap<String, Object>();
   	 	TCMmCooperorgCostDTO dto =new TCMmCooperorgCostDTO();
   	 	dto.setDealCode(dealCode);
   	 	dto.setCostCode(costCode);
    	searchParams.put("dto", dto);
		
        List<TCMmCooperorgCostDTO> list = cooperOrgCostservice.searchTCMmCooperorgCost(searchParams);
        
   	 		if(list!=null &&list.size()>0){
   	 			dto.setCooperorgCode(cooperorgCode);
	 			dto.setContractCode(contractCode);
	 			dto.setCreditPackageName(creditPackageName);
	 			searchParams.put("dto", dto);
	 			cooperOrgCostservice.updateTCMmCooperorgCostbyCode(dto);
   	 		}else{
   	 			dto.setCooperorgCode(cooperorgCode);
   	 			dto.setContractCode(contractCode);
   	 			dto.setCreditPackageName(creditPackageName);
   	 			searchParams.put("dto", dto);
   	 			cooperOrgCostservice.insertTCMmCooperorgCost(dto);
   	 		}
   	 		
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
    }
    
    /**
     * @author zhoupeng
     * @description:把已确认的数据  推送给核心接口
     * @date 2016-04-15 14:42:15
     * @param id
     * @return
     */
    @RequestMapping(value = "/costParameterConfirm")
    @ResponseBody
    public DataMsg costParameterConfirm(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
   	 	String dealCode = (String) this.getParameter("dealCode");
   	 	//String costType =(String) this.getParameter("costType");
   	 	String v_ids =(String) this.getParameter("v_ids");
   	 
   	 	Map<String, Object>  param = new HashMap<String, Object>();
	 	param.put("dealCode", dealCode);//交易流水号
	 	param.put("creditorStatus", CimsConstant.CREDIT_STATUS_WIN);//债权状态
	 	param.put("costStatus", CimsConstant.COST_STATUS_DJ);//结算状态为 待结算
	 	param.put("ids", v_ids);// 交易流水表主键

		try {
			List<CreditDetailDto> list = dealService.getDealDetailListReturn(param);
			if(list!=null &&list.size()>0){
				logger.info("结算申请已发送。。。。");
				dataMsg.setMsg("结算申请已发送，请查看状态！");
				dataMsg.setStatus("ok");
				//推送接口
				settleBalanceService.settleApply(list);
				
			}else{
				dataMsg.setMsg("没有符合申请的债权！请检查数据");
				dataMsg.setStatus("error");
			}
			
		}catch (Exception e) {
			dataMsg.setMsg("结算申请失败！");
			dataMsg.setStatus("error");
			dataMsg.failed(e.getMessage());
			logger.error("", e);

		}
        
        return dataMsg;
    }
    
}
